#!/bin/sh /etc/rc.common
# Copyright (C) 2007 OpenWrt.org

START=99

list_servers() {
	SERVER_PARAMS=" -SER[Shost:"
	config_get host "$1" 'host'
	config_get port "$1" 'port'
	config_get atoken "$1" 'atoken'
	SERVER_PARAMS="${SERVER_PARAMS}""${host}"",Sport:""${port}"
	[ ! $atoken ] && SERVER_PARAMS=${SERVER_PARAMS}"]" || SERVER_PARAMS=${SERVER_PARAMS}",Atoken:${atoken}]"
	eval ${1}_PARAMS=\$SERVER_PARAMS
}

list_tunnels() {
	echo $1 >> /tmp/ngrokc/ngrokc.list
	config_get_bool enabled "$1" 'enabled'
	config_get type "$1" 'type'
	config_get lhost "$1" 'lhost'
	config_get server "$1" 'server'
	config_get lport "$1" 'lport'
	config_get custom_domain "$1" 'custom_domain'
	config_get rport "$1" 'rport'
	config_get dname "$1" 'dname'
	[ -z "$lhost" ] && lhost="127.0.0.1"
	if [ "$enabled" = 1 ]; then
		TUNNEL_PARAMS=" -AddTun[Profile:${1},Type:${type},Lhost:${lhost},Lport:${lport}"
		[ "z""$custom_domain" = "z1" ] && DTYPE="Hostname" || DTYPE="Sdname"
		[ ${type} = "tcp" ] && \
		TUNNEL_PARAMS=${TUNNEL_PARAMS}",Rport:${rport}," || \
		TUNNEL_PARAMS=${TUNNEL_PARAMS}",${DTYPE}:${dname}"
		TUNNEL_PARAMS=${TUNNEL_PARAMS}"]"
		SERVER_PARAMS=`get_servarg $server`
		logger -t "ngrokc" "${server} : ngrokc ${SERVER_PARAMS} ${TUNNEL_PARAMS}"
		CMD_EXIST=`busybox ps -w -w|grep "Profile:${1}" |grep -v grep`
		if [ "z""${CMD_EXIST}" = "z" ] ; then
			exec /usr/bin/ngrokc $SERVER_PARAMS $TUNNEL_PARAMS 2>&1 >/dev/null &
			echo  $! > /tmp/ngrokc/${1}.pid
		fi
		#exec $STDBUF /usr/bin/ngrokc $SERVER_PARAMS $TUNNEL_PARAMS 2>/dev/null 1>/tmp/ngrokc/${1}.log &
	fi
}

get_servarg() {
	eval echo \$${1}_PARAMS
}

start() {
	mkdir -p /tmp/ngrokc
	touch /tmp/ngrokc/running
	# [ -f /usr/lib/coreutils/libstdbuf.so ] && STDBUF="stdbuf -oL " || STDBUF=""
	config_load 'ngrokc'
	config_foreach list_servers 'servers'
	config_foreach list_tunnels 'tunnel'
	set_crontab
}

stop() {
	kill -2 `pidof ngrokc|sed "s/$$//g"` 2>/dev/null
	rm -f /tmp/ngrokc/*
	sleep 2
}

boot() {
	sleep 10
	start
}

set_crontab() {
	[ -f /etc/crontabs/root ] || touch /etc/crontabs/root
	interval=`uci get ngrokc.main.check_interval`
	ngrokc_cron=`cat /etc/crontabs/root | grep "/etc/init.d/ngrokc start"`
	if [ "${interval}" != "0" ] ; then
		ngrokc_new="*/${interval} * * * * /etc/init.d/ngrokc start"
		if [ "z${ngrokc_cron}" != "z${ngrokc_new}" ] ; then
			cat /etc/crontabs/root | grep -v "/etc/init.d/ngrokc start" > /tmp/crontabs_ngrokc
			echo "" >> /tmp/crontabs_oscam
			echo "*/${interval} * * * * /etc/init.d/ngrokc start" >> /tmp/crontabs_ngrokc
			cat /tmp/crontabs_ngrokc | grep -v ^$ > /etc/crontabs/root
			/etc/init.d/cron restart
		fi
	else
		if [ "z""${ngrokc_cron}" != "z" ] ; then
			cat /etc/crontabs/root | grep -v "/etc/init.d/ngrokc start" > /tmp/crontabs_ngrokc
			cat /tmp/crontabs_ngrokc | grep -v ^$ > /etc/crontabs/root
			/etc/init.d/cron restart
		fi
	fi
}
